package com.atguigu.chapter;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @ClassName: WordCount
 * @Description:
 * @Author: kele
 * @Date: 2021/3/31 10:33
 **/
public class WordCount {

    public static void main(String[] args) throws Exception {

        //1、获取执行环境
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();

        //2、读取文件
        DataSource<String> ds = environment.readTextFile("in/wc.txt");

        //3、处理数据
        FlatMapOperator<String, Tuple2<String, Integer>> ds1 = ds.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = line.split(" ");

                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1));
                }

            }
        });

        //没有reducebykey，只能用groupby+sum
        UnsortedGrouping<Tuple2<String, Integer>> ds2 = ds1.groupBy(0);
        AggregateOperator<Tuple2<String, Integer>> result = ds2.sum(1);

        result.print();

    }
}
